package com.lanchewuyou.user.driver.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.lanchewuyou.user.driver.R;
import com.lanchewuyou.user.driver.Utils.TUtils;
import com.lanchewuyou.user.driver.bean.Company;
import com.lanchewuyou.user.driver.bean.CompanyDB;
import com.lanchewuyou.user.driver.bean.FourS;
import com.lanchewuyou.user.driver.bean.FoursDB;
import com.lanchewuyou.user.driver.lipeiui.LiPeiMainActivity;
import com.lanchewuyou.user.driver.modul.Config;
import com.lanchewuyou.user.driver.modul.OkHttpClientManager;
import com.squareup.okhttp.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 欢迎页,存取4s店信息和保险公司信息到数据库
 */
public class WelcomeActivity extends AppCompatActivity {
    private CompanyDB companyDB;
    private FoursDB foursDB;
    private String name, password;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        new Timer().schedule(new TimerTask() {
            public void run() {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        }, 500);//停留时间
        companyDB = CompanyDB.getInstance(this);
        foursDB = FoursDB.getInstance(this);
        SharedPreferences sharedPreferences = getSharedPreferences(Config.PASSWORD_PATH, Activity.MODE_PRIVATE);
        name = sharedPreferences.getString("mobile", "");
        password = sharedPreferences.getString("password", "");
    }

    /**
     * 检查数据库版本，版本号不变则直接跳转，变了则改变版本号，删除当前数据，插入新的数据
     */
    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    SharedPreferences sp = getSharedPreferences(Config.DATABASE, Activity.MODE_PRIVATE);
                    final String companydatabaseid = sp.getString("companydatabaseid", "");
                    Log.d("version1", companydatabaseid);
                    final String foursdatabaseid = sp.getString("foursdatabaseid", "");
                    Log.d("version2", companydatabaseid);
                    final SharedPreferences.Editor editor = sp.edit();
                    OkHttpClientManager.getAsyn(Config.DATABASE_URL + "insure", new OkHttpClientManager.StringCallback() {
                        @Override
                        public void onFailure(Request request, IOException e) {
                            TUtils.showShort(WelcomeActivity.this, "服务器出了点问题");
                        }

                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                String version = jsonObject.getString("version");
                                Log.d("version3", "数据库版本无改变");
                                if (companydatabaseid.equals(version)) {
                                    Log.d("version", version);
                                } else {
                                    companyDB.wipeCompany();
                                    editor.putString("companydatabaseid", version);
                                    editor.commit();
                                    insertCompanyDatabase();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    OkHttpClientManager.getAsyn(Config.DATABASE_URL + "shop", new OkHttpClientManager.StringCallback() {
                        @Override
                        public void onFailure(Request request, IOException e) {
                            TUtils.showShort(WelcomeActivity.this, "服务器出了点问题");
                        }

                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                String version = jsonObject.getString("version");
                                Log.d("version", version);
                                if (foursdatabaseid.equals(version)) {
                                    Log.d("version", "数据库版本无改变");
                                    sign();
                                } else {
                                    foursDB.wipeFours();
                                    editor.putString("foursdatabaseid", version);
                                    editor.commit();
                                    insertFoursDatabase();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    break;
                default:
                    break;
            }

        }
    };

    /**
     * 登录方法，成功则直接跳转，失败则删除文件里存储的用户名和密码直接跳转登录界面
     */
    private void sign() {
        OkHttpClientManager.getAsyn(Config.SIGN_URL + "&mobile=" + name + "&password=" + password,
                new OkHttpClientManager.StringCallback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        TUtils.showShort(WelcomeActivity.this, "服务器出了点问题");
                        Intent intent = new Intent(WelcomeActivity.this, SigninActivity.class);
                        startActivity(intent);
                        finish();
                        overridePendingTransition(R.anim.right_in, R.anim.not_move);
                    }

                    @Override
                    public void onResponse(String response) {
                        Log.d("WELCOME", response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString("status");
                            if (status.equals("1")) {
                                Intent intent = new Intent(WelcomeActivity.this, LiPeiMainActivity.class);
                                startActivity(intent);
                                finish();
                                overridePendingTransition(R.anim.right_in, R.anim.not_move);
                            } else {
                                SharedPreferences sharedPreferences = getSharedPreferences(Config.PASSWORD_PATH, Activity.MODE_PRIVATE);
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.remove("drivername");
                                editor.remove("password");
                                editor.remove("mobile");
                                editor.remove("driverid");
                                editor.remove("driverpic");
                                editor.commit();
                                Intent intent = new Intent(WelcomeActivity.this, SigninActivity.class);
                                startActivity(intent);
                                finish();
                                overridePendingTransition(R.anim.right_in, R.anim.not_move);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 准备保险公司数据方法
     */
    private void insertCompanyDatabase() {
        OkHttpClientManager.getAsyn(Config.COMPANY_URL, new OkHttpClientManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.d("WELCOME", e.toString());
            }

            @Override
            public void onResponse(String response) {
                Log.d("WELCOME", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray insure = jsonObject.getJSONArray("list");
                    Log.d("WELCOME", insure.toString());
                    for (int i = 0; i < insure.length(); i++) {
                        Company company = new Company();
                        JSONObject companyJson = insure.getJSONObject(i);
                        company.setId(companyJson.getString("id"));
                        company.setName(companyJson.getString("name"));
                        company.setAddress(companyJson.getString("address"));
                        company.setShortName(companyJson.getString("shortname"));
                        companyDB.saveCompany(company);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    /**
     * 准备4s店数据方法
     */

    private void insertFoursDatabase() {
        OkHttpClientManager.getAsyn(Config.FOURS_URL, new OkHttpClientManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.d("WELCOME", e.toString());
            }

            @Override
            public void onResponse(String response) {
                Log.d("WELCOME", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray shop = jsonObject.getJSONArray("list");
                    Log.d("WELCOME", shop.toString());
                    for (int i = 0; i < shop.length(); i++) {
                        FourS fourS = new FourS();
                        JSONObject foursJson = shop.getJSONObject(i);
                        fourS.setId(foursJson.getString("id"));
                        fourS.setName(foursJson.getString("name"));
                        fourS.setAddress(foursJson.getString("address"));
                        fourS.setShortname(foursJson.getString("shortname"));
                        fourS.setRegional(foursJson.getString("regional"));
                        fourS.setBrandid(foursJson.getString("brand_id"));
                        foursDB.saveFours(fourS);
                    }
                    sign();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

